use crate::extension::index::scheme_manager::Scheme;
use crate::config::app_error::{AppError, AppResult};
use std::slice::Iter;
use std::sync::RwLock;

pub trait SchemeWatcherManager {
    fn register(&self, watcher: Box<dyn SchemeWatcher>) -> AppResult<()>;

    fn unregister(&self, watcher: Box<dyn SchemeWatcher>) -> AppResult<()>;

    fn watchers(&self) -> AppResult<Vec<Box<dyn SchemeWatcher>>>;
}

pub trait SchemeWatcher {
    fn on_change(&self, event: Box<dyn ChangeEvent>);
}

pub trait ChangeEvent {}

pub struct SchemeRegistered {
    new_scheme: Scheme,
}
impl SchemeRegistered {
    pub(crate) fn new(scheme: Scheme) -> Self {
        SchemeRegistered { new_scheme: scheme }
    }
}
impl ChangeEvent for SchemeRegistered {}

pub struct SchemeUnregistered {
    deleted_scheme: Scheme,
}
impl SchemeUnregistered {
    pub(crate) fn new(deleted_scheme: Scheme) -> Self {
        SchemeUnregistered { deleted_scheme }
    }
}

impl ChangeEvent for SchemeUnregistered {}
pub struct DefaultSchemeWatcherManager {
    // 使用 RwLock 提供内部可变性，支持多线程安全的读写操作
    watchers: RwLock<Vec<Box<dyn SchemeWatcher>>>,
}

impl DefaultSchemeWatcherManager {
    pub fn new() -> Self {
        DefaultSchemeWatcherManager {
            watchers: RwLock::new(Vec::new()),
        }
    }
}

impl SchemeWatcherManager for DefaultSchemeWatcherManager {
    fn register(&self, watcher: Box<dyn SchemeWatcher>) -> AppResult<()> {
        let mut watchers = self.watchers.write()
            .map_err(|_| AppError::InternalServerError("Failed to acquire write lock on watchers".to_string()))?;
        watchers.push(watcher);
        Ok(())
    }

    fn unregister(&self, _watcher: Box<dyn SchemeWatcher>) -> AppResult<()> {
        // 由于 Box<dyn SchemeWatcher> 没有实现 PartialEq，暂时不实现具体逻辑
        // 在实际使用中，可能需要为 SchemeWatcher 添加 ID 或其他标识符来进行比较
        todo!("unregister implementation requires SchemeWatcher to have identity comparison")
    }

    fn watchers(&self) -> AppResult<Vec<Box<dyn SchemeWatcher>>> {
        // 注意：由于 Box<dyn SchemeWatcher> 不能被克隆，这里返回空向量
        // 在实际实现中，可能需要重新设计 API 或使用 Arc<dyn SchemeWatcher>
        let _watchers = self.watchers.read()
            .map_err(|_| AppError::InternalServerError("Failed to acquire read lock on watchers".to_string()))?;

        // 暂时返回空向量，实际实现需要考虑如何处理不可克隆的 trait 对象
        Ok(Vec::new())
    }
}
